<template>
    <div class="prescription">
        <el-table :data="tableData" class="tb-edit" border style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column label="序号" min-width="50px">
                <template slot-scope="scope">
                    <span v-if="scope.row.edit">
                        {{ scope.$index + 1 }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column :key="item.label" :label="item.label" :min-width="item.width || ''" v-for="(item, index) in config.column">
                <template slot-scope="scope">

                  <search-input :searchName="scope.row[item.name]"  :key="scope.row.id":ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'searchInput'" :config="sConfig" :controls="false" :disabled="!scope.row.edit" v-model="scope.row[item.key]"  placeholder="" @change="(row) => { searchChange(row, scope.$index); nextFocus(scope.$index, index)}"></search-input>
                  <el-select :ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'select'"

                               placeholder="" :disabled="!scope.row.edit" :controls="false" v-model="scope.row[item.key]"  @change="(row) => { selectChange(scope.row, scope.$index); nextFocus(scope.$index, index)}">


                    <el-option label="月" :value="2"></el-option>
                    <el-option label="天" :value="3"></el-option>

                  </el-select>

                    <span v-if="item.type == 'text'">
                      {{ scope.row[item.key] }}


                    </span>
                  <span v-if="item.type == 'texts'"  >
                    <span v-for="(item,index) in scope.row.executionTimes" style="display: block">
                      <span v-if="scope.row.unit == 2&&item[0]">
                           {{item[0]}}日
                      </span>
                      <span v-if=" item[1]">
                        {{item[1]}} 时
                      </span>
                      <span v-if="item[2]">
                        {{item[2]}}分
                      </span>
                    </span>

                 <el-popover
                   v-if="scope.row.edit && scope.row.markId"
                   placement="bottom"

                   v-model="scope.row.index"
                   trigger="click"
                  >
          	<el-form  label-width="240px" >
				<el-form-item label="周期内执行时间"   >
					<div  v-for="(item,index) in scope.row.executionTime" class="timeBox">
						<template v-if="scope.row.unit == 2">
							<el-input-number controls-position="right" style="width:84px" v-model="item.d" :min="0" :max="31"></el-input-number> 天
						</template>
						<el-input-number controls-position="right" style="width:84px" v-model="item.h" :min="0" :max="24"></el-input-number> 时
						<el-input-number controls-position="right" style="width:84px" v-model="item.m" :min="0" :max="60"></el-input-number> 分
            <!-- <el-time-picker v-model="item.value" value-format="timestamp"></el-time-picker> -->
						<i class="el-icon-minus" v-if="index" @click="delTimeItem1(scope.row,index)"></i>
						<i class="el-icon-plus" v-else @click="add(scope.row)"></i>
					</div>
				</el-form-item>
			</el-form>

 <div style="text-align: right; margin: 0">

    <el-button size="mini" type="text" @click="scope.row.index=false">取消</el-button>
    <el-button type="primary" size="mini" @click="addProject(scope.row,scope.$index), pflag && (scope.row.index=false)"  >确定</el-button>
  </div>

  <el-button slot="reference" style="border:0 !important;background: none;float: right"  @click="addtime(scope.row)">  <i class="el-icon-plus" v-if="!scope.row.executionTimes  "></i><i class="el-icon-edit" v-if="scope.row.executionTimes"></i></el-button>





  </el-popover>
                    </span>

                  <el-input-number :ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'numbertext'"   :disabled="scope.row.ischarge=='否' || scope.row.charged":controls="false" v-model="scope.row[item.key]" :min="item.min || 0" :max="item.max" @keyup.enter.native="nextFocus(scope.$index, index)"></el-input-number>
                  <el-input :ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'input'" :disabled="!scope.row.edit" v-model="scope.row[item.key]" @keyup.enter.native="nextFocus(scope.$index, index)"></el-input>
                    <el-input-number :ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'number'"  :controls="false" v-model="scope.row[item.key]" :min="item.min || 0" :max="item.max" @keyup.enter.native="nextFocus(scope.$index, index)" ></el-input-number>
                    <el-date-picker :ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'date'" v-model="scope.row[item.key]" type="date" @change="nextFocus(scope.$index, index)"></el-date-picker>
                  <el-date-picker :ref="'input_' + scope.$index + '_' + index" v-if="item.type == 'datetime'" v-model="scope.row[item.key]" type="datetime" @change="nextFocus(scope.$index, index)"></el-date-picker>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="50px" align="center">
                <template slot-scope="scope">

                    <el-button v-if="scope.row.edit && scope.row.markId" type="text" @click="handleDelete(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

    </div>
</template>

<script>
    import request from '@/utils/request'
    import SearchInput from "../../../components/searchInputs";
    import {disableCarePlanTemplateContent,enableCarePlanTemplateContent}  from "@/api/template"
    export default {
        name: "prescription",
        components: {SearchInput},
        props: {
            value: {
                type: Array,
                default: ''
            },
            config: {
                type: Object,
                default: {}
            },
            fixed: {
                type: Boolean,
                default: false
            },
            defaultLength: {
                type: Number,
                default: 8
            },
            marks:{
                type: String,
                default: 8
            },

        },
        data(){

            return {
                pflag:false,


                // addProjectForm: {
              //   executionTimes:[{
              //     d:'',
              //     h:'',
              //     m:''
              //   }]
              // },
                sConfig: {
                    api: '/sinohis/pension/fee/itemmanager/searchAllMealItemInfos',
                    method: 'GET',
                    postKey: 'condition',
                    label: 'name',
                    value: 'markId',
                    values: ['mark','meal'],
                    data: {mark:this.marks},
                    keys: [
                        { name: '名称', key: 'name' },
                        { name: '价格', key: 'fee' },
                        { name: '类型', key: 'ismeal' },
                    ]
                },
                tableData: [],
                groupIndex: 0,
                FRI: 0,
                FII: 0,
                newLine: 0,
                disabled:false,
            }
        },
        mounted() {
            console.log(this.marks)

            this.parentHandleclick(this.value)
            this.setList()
            this.$nextTick(() => {
                console.log(this.$refs)
            })
        },
        methods: {
          add(data){
              console.log(data)

                  data.executionTime.push(
                      {
                          d:undefined,
                          h:undefined,
                          m:undefined

                      }


                  )


          },

          delTimeItem1(row,index){
             row.executionTime.splice(index, 1)
          },
          selectChange(row){

              row.executionTimes = undefined


          },
            disableCarePlanTemplateContent(row){
                let tcMark = row.tcMark
                disableCarePlanTemplateContent({tcMark}).then(res => {
                    this.$baseMessage('已禁用', 'success')
                    row.disabled=true
                })
            },
            enableCarePlanTemplateContent(row){
                let tcMark = row.tcMark
                enableCarePlanTemplateContent({tcMark}).then(res => {
                    this.$baseMessage('已启用', 'success')
                    row.disabled=false
                })
            },
          addProject(value,index,id){
              console.log(value)
                 let times =[...value.executionTime]
                let timeList = []
                let timeString = []
                for(let i=0; i<times.length; i++){
                  let item = times[i]
                  let itemList = []
                  itemList.push(item.d >= 0 ? item.d : 0)
                  itemList.push(item.h >= 0 ? item.h : 0)
                  itemList.push(item.m >= 0 ? item.m : 0)
                  timeList.push(itemList)
                  let timeStringItem = (item.d >= 0 ? item.d : 0) + '' + item.h + '' + item.m
                  console.log(timeStringItem)
                  if(timeStringItem.length > 6){
                      this.pflag=false
                    this.$baseMessage('执行时间不能为空', 'error')
                    return false
                  }
                  timeString.push(timeStringItem)
                }
                if(Array.from(new Set(timeString)).length < timeString.length){
                  this.$baseMessage('执行时间不能重复', 'error')
                  return false
                }
                let addForm ={...value}
               this.$parent.$parent.GenerateNursePlanCreatorGenerateNursePlanCreator.items[index].executionTimes=(timeList)
               console.log( this.tableData)
               this.pflag=true

                // addForm.executionTimes = timeList



                // if(this.isEditProject){
                //   modifyExtraItemPlanToTemplate(addForm).then(res => {
                //     this.getProjectlist()
                //     this.addProjectVisible = false
                //   })
                // }else{
                //   addExtraItemPlanToTemplate(addForm).then(res => {
                //     this.getProjectlist()
                //     this.addProjectVisible = false
                //   })
                // }



          },
            setList(){
                let list = [...this.tableData]
                let length = this.defaultLength - list.length
                for(let i = 0; i < length; i++){

                    let row = JSON.parse(JSON.stringify(this.config.data))

                    list.push(row)
                  console.log(list)
                }
                list[0].edit = true

            },
            searchChange(row, index){



                console.log(row)
                 if(row.charged==true){

                   var  ischange="是"
                 }else {

                     var ischange='否'
                 }
                let arr=
                    {
                        meal:row.meal,
                        startExecTime:new Date(),
                        unit:2,
                        mealItem:row.meal,
                        nursingItemMark:row.mark,
                        charge:row.charged,
                        ischarge:ischange,
                        price:row.fee,
                    }


                  this.tableData[index] = Object.assign(this.tableData[index], arr)
            },
            handleDelete(index){
                 this.tableData.splice(index, 1)
                  this.tableData.push( JSON.parse(JSON.stringify(this.config.data)))
                // this.setList()
            },
            checkArr(list = this.tableData){
                for(let i=0; i<list.length; i++){
                    let item = list[i]
                    let sum = 0
                    Object.keys(item).forEach(key => {
                        if(item[key]){
                            sum++
                        }
                    })
                    if(sum > 2){
                        if(!list[i + 1]){
                            let  row= JSON.parse(JSON.stringify(this.config.data))

                            list.push({...row})
                        }



                        list[i]['key']='a'+i
                        list[i]['edit'] = true
                        list[i + 1]['edit'] = true
                        list[i]['checkEdit'] = true
                    }
                }
            },
            tableRowClassName({row, rowIndex}) {
                return 'color' + row.a005
            },
            addtime(row){

                let c=[]
                    console.log(row.executionTimes)
                        if(row.executionTimes){
                            for (let  i=0;i<row.executionTimes.length;i++){

                                let b = {}
                                let d = row.executionTimes[i]
                                b.d = parseInt(d[0])
                                b.h = parseInt(d[1])
                                b.m = parseInt(d[2])
                                c.push(b)
                                row.executionTime = c
                            }
                        }else {
                            row.executionTime = [{
                                d:undefined,
                                h:undefined,
                                m:undefined

                            }]
                        }
             },
            parentHandleclick(list) {
                list=JSON.parse(JSON.stringify(list))
                console.log(list)
                    for(let item in list) {
                        console.log(list[item].executionTimes)
                        list[item].executionTime = list[item].executionTimes

                        list[item].startExecTime = new Date()

                    }


                this.tableData = list
                console.log(this.tableData)
                this.newLine = list.length > this.defaultLength ? list.length : this.defaultLength
                this.setList()
            },
            grouping(){
                let list = this.tableData.filter(item => item.a004)
                if(this.checkGroup(list)){
                    this.tableData.forEach(item => {
                        if(item.a004){
                            item.a004 = false
                            item.a005 = this.groupIndex + 1
                        }
                    })
                    this.groupIndex ++
                }else{
                    this.$message.error('频率和用法不能为空，且组内需要一致')
                }
            },
            ungroup(){
                this.tableData.forEach(item => {
                    if(item.a004){
                        item.a004 = false
                        item.a005 = ''
                    }
                })
            },
            checkGroup(a){
                for(let i=0; i<a.length; i++){
                    if(i){
                        if(!a[i].a007 || !a[i].a008 || a[i].a007 != a[i-1].a007 || a[i].a008 != a[i-1].a008){
                            return false
                        }
                    }
                }
                return true
            },
            nextFocus($index, index){

                let list = this.tableData

                console.log(list)

                for(let i=0;i<1;i++){

                    list[$index].executionTime = [{
                        d:undefined,
                        h:undefined,
                        m:undefined

                    }]


                }

                console.log(this.$refs)
                setTimeout(() => {
                    this.FRI = $index
                    this.FII = index
                    let item = this.getNext()
                    console.log(item)
                    item && (item.focus())
                    console.log($index, index)
                }, 200)
            },
            getNext(){
                let x;
                if(this.fixed){
                    if(this.FRI == this.newLine - 1 && this.FII == this.config.column.length - 1){

                        x = 0
                    }else{
                        x = this.FRI >= this.newLine ? 0 : 1
                    }
                }else{
                    x = 0
                }
                for(let i=this.FII + 1; i<this.config.column.length; i++){
                    this.FII = i
                    let ref = 'input_' + this.FRI + '_' + i
                    let doms = this.$refs[ref]
                    if(doms){
                        return doms[x]
                    }
                }
                this.FRI++
                this.FII = 0
                let ref = 'input_' + this.FRI + '_' + this.FII
                let doms = this.$refs[ref]
                if(doms){
                    return doms[x]
                }
                return false
            }
        },
        watch: {
            // value: function(val){
            //     this.tableData = val
            //     this.setList()
            // },
            tableData: {
                handler(list){
                    console.log(list)
                    this.checkArr(list)

                     this.$emit('input', list.filter(item => item.markId))
                },
                deep: true
            }
        },
        beforeDestroy(){

        }
    };
</script>
<style scoped>
    .prescription >>> .el-input{width: 100%;}
    .prescription >>> .el-input .el-input__inner{padding: 0 4px;height: 20px;line-height: 20px;border-color: rgba(0,0,0,0);background: none;transition: all 0.4s;}
    .prescription >>> .el-input .el-input__inner:hover{border-color: rgba(0,0,0,0);}
    .prescription >>> .el-input .el-input__inner:focus{background: #fff;border-color: #4c6ca7;}
    .prescription >>> .cell{padding-left: 5px;padding-right: 5px;}
    .prescription >>> .cell>span{margin-left: 5px;}
    .prescription >>> .is-center .cell{padding-left: 0;padding-right: 0;}
    .prescription >>> thead .cell{padding-left: 9px;padding-right: 5px;}

    .prescription >>> .el-textarea{width: 100%;}
    .prescription >>> .el-textarea__inner{padding: 0 4px;height: 20px;line-height: 20px;border-color: rgba(0,0,0,0);background: none;transition: all 0.4s;resize: none;}
    .prescription >>> .el-textarea__inner:focus{background: #fff;border-color: #4c6ca7;}
    .prescription >>> .el-table.tb-edit .cell{padding-top: 0;padding-bottom: 0;}
    .prescription >>> .el-table.tb-edit td{padding: 0;height: 30px;}
    .prescription >>> .el-input.is-disabled .el-input__inner {cursor: auto;}
    .prescription >>> .el-textarea.is-disabled .el-textarea__inner {cursor: auto;}
    .prescription >>> .el-input__suffix{display: none;}

    .prescription >>> .el-checkbox.is-disabled .el-checkbox__input{opacity: 0;cursor: auto;}
    .prescription >>> .el-checkbox.is-disabled .el-checkbox__inner{cursor: auto;}

    .prescription >>> .el-table .color1 {background: #f0f9eb;}
    .prescription >>> .el-table .color2 {background: #fdf6ec;}
    .prescription >>> .el-table .color3 {background: #feeff0;}
    .prescription >>> .el-table .color4 {background: #ecf5ff;}

    .btnAll{padding-top: 20px;}

    .prescription >>> .el-input-number{width: auto;}
    .prescription >>> .el-date-editor .el-input__icon{display: none;}
    .timeBox{margin-bottom: 10px;}
    .timeBox:last-child{margin-bottom: 0;}
    .timeBox i{cursor: pointer;color: #1890ff;margin-left: 10px;}
    .itemBox{}
    .itemBox span{display: inline-block;overflow: hidden; white-space: nowrap; text-overflow: ellipsis;width: 120px;}
    .itemBox span:first-child{width: 130px;}
</style>
